// pages/Dashboard/TrialComponent.jsx
import React, { useState } from 'react';
import { 
  Grid,
  Typography,
  Button,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  CircularProgress,
  Chip,
  Pagination,
  Box
} from '@mui/material';
import ElectricBoltIcon from '@mui/icons-material/ElectricBolt';
import { useAuth } from 'contexts/AuthContext';
import { paperSx } from './sxobjects';

// Mock data generator with randomization
const generateMockFSBORecords = (count) => {
  const firstNames = ['John', 'Jane', 'Michael', 'Sarah', 'David', 'Lisa', 'Robert', 'Amanda', 'James', 'Emily'];
  const lastNames = ['Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Garcia', 'Miller', 'Davis', 'Rodriguez', 'Martinez'];
  const companies = ['', 'Smith Real Estate', 'Sunshine Properties', 'Metro Homes', 'Valley Realty', ''];
  const cities = ['Los Angeles', 'San Francisco', 'San Diego', 'Sacramento', 'Oakland', 'Fresno', 'Long Beach', 'Bakersfield'];
  const states = ['CA', 'TX', 'NY', 'FL', 'WA', 'OR', 'NV', 'AZ'];
  const countries = ['USA', 'Canada'];
  const howFound = ['Google', 'Referral', 'Advertisement', 'Social Media', 'Direct Mail', 'Website'];

  const records = [];
  for (let i = 1; i <= count; i++) {
    const firstName = firstNames[Math.floor(Math.random() * firstNames.length)];
    const lastName = lastNames[Math.floor(Math.random() * lastNames.length)];
    const city = cities[Math.floor(Math.random() * cities.length)];
    const state = states[Math.floor(Math.random() * states.length)];
    
    records.push({
      cID: i,
      cString: `FSBO${String(i).padStart(4, '0')}`,
      cBillCompany: companies[Math.floor(Math.random() * companies.length)],
      cBillFname: firstName,
      cBillLname: lastName,
      cBillAddress1: `${Math.floor(Math.random() * 9999) + 1} ${['Main', 'Oak', 'Pine', 'Elm', 'Cedar'][Math.floor(Math.random() * 5)]} St`,
      cBillAddress2: Math.random() > 0.7 ? `Apt ${Math.floor(Math.random() * 200) + 1}` : null,
      cBillCity: city,
      cBillState: state,
      cBillZip: `${Math.floor(Math.random() * 90000) + 10000}`,
      bill_county: `${city} County`,
      cBillCountry: countries[Math.floor(Math.random() * countries.length)],
      cPhone: `(${Math.floor(Math.random() * 900) + 100}) ${Math.floor(Math.random() * 900) + 100}-${Math.floor(Math.random() * 9000) + 1000}`,
      cFax: Math.random() > 0.6 ? `(${Math.floor(Math.random() * 900) + 100}) ${Math.floor(Math.random() * 900) + 100}-${Math.floor(Math.random() * 9000) + 1000}` : null,
      cHow: howFound[Math.floor(Math.random() * howFound.length)],
      cEmail: `${firstName.toLowerCase()}.${lastName.toLowerCase()}@${['gmail', 'yahoo', 'hotmail', 'outlook'][Math.floor(Math.random() * 4)]}.com`,
      cDateSince: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
      cUpdateDate: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
      cWholesaleDiscount: Math.random() > 0.8 ? Math.floor(Math.random() * 20) + 5 : null,
    });
  }
  return records;
};

const TrialComponent = () => {
  const { user } = useAuth() || {};
  const [loading, setLoading] = useState(false);
  const [records, setRecords] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const recordsPerPage = 10;

  // Safely destructure user object
  const { role = 'user', account = {} } = user || {};
  const { planType = 'basic' } = account;

  // Color mappings
  const getRoleColor = (role) => {
    switch (role) {
      case 'admin': return '#238636'; // green
      case 'superadmin': return '#58a6ff'; // blue
      default: return '#f0f6fc'; // off-white
    }
  };

  const getPlanColor = (planType) => {
    switch (planType) {
      case 'premium': return '#fb8500'; // orange
      case 'pro': return '#58a6ff'; // blue
      default: return '#f0f6fc'; // off-white
    }
  };

  // Record limits based on plan
  const getRecordLimit = (planType) => {
    switch (planType) {
      case 'premium': return 50;
      case 'pro': return 100;
      default: return 10;
    }
  };

  const handlePullRecords = async () => {
    setLoading(true);
    
    // 3 second timeout simulation
    setTimeout(() => {
      const limit = getRecordLimit(planType);
      const mockRecords = generateMockFSBORecords(limit);
      setRecords(mockRecords);
      setCurrentPage(1);
      setLoading(false);
    }, 3000);
  };

  const handlePageChange = (event, value) => {
    setCurrentPage(value);
  };

  // Calculate pagination
  const indexOfLastRecord = currentPage * recordsPerPage;
  const indexOfFirstRecord = indexOfLastRecord - recordsPerPage;
  const currentRecords = records.slice(indexOfFirstRecord, indexOfLastRecord);
  const totalPages = Math.ceil(records.length / recordsPerPage);

  return (
    <Grid container spacing={3}>
      <Grid item xs={12}>
        <Paper {...paperSx}>
          <Box sx={{ p: 3 }}>
            {/* Show loading if no user */}
            {!user ? (
              <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
                <CircularProgress 
                  sx={{ color: '#58a6ff' }}
                  size={60}
                />
              </Box>
            ) : (
              <>
                {/* Header Section */}
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
                  <Typography variant="h5" sx={{ color: '#58a6ff', fontWeight: 600 }}>
                    FSBO Records Dashboard
                  </Typography>
                  
                  <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
                    <Chip 
                      label={`Role: ${role}`} 
                      sx={{ 
                        backgroundColor: getRoleColor(role), 
                        color: role === 'user' ? '#21262d' : '#ffffff',
                        fontWeight: 500
                      }} 
                    />
                    <Chip 
                      label={`Plan: ${planType}`} 
                      sx={{ 
                        backgroundColor: getPlanColor(planType), 
                        color: planType === 'basic' ? '#21262d' : '#ffffff',
                        fontWeight: 500
                      }} 
                    />
                  </Box>
                </Box>

                {/* Pull Records Button */}
                <Box sx={{ display: 'flex', justifyContent: 'center', mb: 4 }}>
                  <Button
                    variant="contained"
                    startIcon={<ElectricBoltIcon />}
                    onClick={handlePullRecords}
                    disabled={loading}
                    sx={{
                      backgroundColor: '#fb8500',
                      color: '#ffffff',
                      fontWeight: 600,
                      fontSize: '1.1rem',
                      px: 4,
                      py: 1.5,
                      borderRadius: 2,
                      '&:hover': {
                        backgroundColor: '#e07600',
                      },
                      '&:disabled': {
                        backgroundColor: '#30363d',
                        color: '#8b949e',
                      }
                    }}
                  >
                    Pull Current FSBO Records
                  </Button>
                </Box>

                {/* Loading State for button click */}
                {loading && (
                  <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
                    <CircularProgress 
                      sx={{ color: '#58a6ff' }}
                      size={60}
                    />
                  </Box>
                )}

                {/* Records Table */}
                {!loading && records.length > 0 && (
                  <>
                    <TableContainer 
                      component={Paper} 
                      sx={{ 
                        backgroundColor: '#0d1117', 
                        border: '1px solid #30363d',
                        borderRadius: 2,
                        mb: 3
                      }}
                    >
                      <Table>
                        <TableHead>
                          <TableRow sx={{ backgroundColor: '#21262d' }}>
                            <TableCell sx={{ color: '#58a6ff', fontWeight: 600, border: '1px solid #30363d' }}>ID</TableCell>
                            <TableCell sx={{ color: '#58a6ff', fontWeight: 600, border: '1px solid #30363d' }}>Code</TableCell>
                            <TableCell sx={{ color: '#58a6ff', fontWeight: 600, border: '1px solid #30363d' }}>Name</TableCell>
                            <TableCell sx={{ color: '#58a6ff', fontWeight: 600, border: '1px solid #30363d' }}>Company</TableCell>
                            <TableCell sx={{ color: '#58a6ff', fontWeight: 600, border: '1px solid #30363d' }}>Email</TableCell>
                            <TableCell sx={{ color: '#58a6ff', fontWeight: 600, border: '1px solid #30363d' }}>Phone</TableCell>
                            <TableCell sx={{ color: '#58a6ff', fontWeight: 600, border: '1px solid #30363d' }}>Address</TableCell>
                            <TableCell sx={{ color: '#58a6ff', fontWeight: 600, border: '1px solid #30363d' }}>City, State</TableCell>
                            <TableCell sx={{ color: '#58a6ff', fontWeight: 600, border: '1px solid #30363d' }}>How Found</TableCell>
                            <TableCell sx={{ color: '#58a6ff', fontWeight: 600, border: '1px solid #30363d' }}>Date Added</TableCell>
                          </TableRow>
                        </TableHead>
                        <TableBody>
                          {currentRecords.map((record) => (
                            <TableRow key={record.cID} sx={{ '&:hover': { backgroundColor: '#30363d' } }}>
                              <TableCell sx={{ color: '#f0f6fc', border: '1px solid #30363d' }}>{record.cID}</TableCell>
                              <TableCell sx={{ color: '#f0f6fc', border: '1px solid #30363d' }}>{record.cString}</TableCell>
                              <TableCell sx={{ color: '#f0f6fc', border: '1px solid #30363d' }}>
                                {record.cBillFname} {record.cBillLname}
                              </TableCell>
                              <TableCell sx={{ color: '#f0f6fc', border: '1px solid #30363d' }}>
                                {record.cBillCompany || 'N/A'}
                              </TableCell>
                              <TableCell sx={{ color: '#f0f6fc', border: '1px solid #30363d' }}>{record.cEmail}</TableCell>
                              <TableCell sx={{ color: '#f0f6fc', border: '1px solid #30363d' }}>{record.cPhone}</TableCell>
                              <TableCell sx={{ color: '#f0f6fc', border: '1px solid #30363d' }}>
                                {record.cBillAddress1}
                                {record.cBillAddress2 && <><br />{record.cBillAddress2}</>}
                              </TableCell>
                              <TableCell sx={{ color: '#f0f6fc', border: '1px solid #30363d' }}>
                                {record.cBillCity}, {record.cBillState}
                              </TableCell>
                              <TableCell sx={{ color: '#f0f6fc', border: '1px solid #30363d' }}>{record.cHow}</TableCell>
                              <TableCell sx={{ color: '#f0f6fc', border: '1px solid #30363d' }}>
                                {new Date(record.cDateSince).toLocaleDateString()}
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </TableContainer>

                    {/* Pagination */}
                    {totalPages > 1 && (
                      <Box sx={{ display: 'flex', justifyContent: 'center' }}>
                        <Pagination
                          count={totalPages}
                          page={currentPage}
                          onChange={handlePageChange}
                          color="primary"
                          sx={{
                            '& .MuiPaginationItem-root': {
                              color: '#f0f6fc',
                              borderColor: '#30363d',
                              '&:hover': {
                                backgroundColor: '#30363d',
                              },
                              '&.Mui-selected': {
                                backgroundColor: '#58a6ff',
                                color: '#ffffff',
                                '&:hover': {
                                  backgroundColor: '#1f6feb',
                                }
                              }
                            }
                          }}
                        />
                      </Box>
                    )}

                    {/* Records Info */}
                    <Box sx={{ mt: 2, textAlign: 'center' }}>
                      <Typography variant="body2" sx={{ color: '#8b949e' }}>
                        Showing {indexOfFirstRecord + 1}-{Math.min(indexOfLastRecord, records.length)} of {records.length} records
                        {planType !== 'pro' && (
                          <span style={{ color: '#fb8500' }}> • Upgrade for more records</span>
                        )}
                      </Typography>
                    </Box>
                  </>
                )}

                {/* Empty State */}
                {!loading && records.length === 0 && (
                  <Box sx={{ textAlign: 'center', py: 8 }}>
                    <Typography variant="h6" sx={{ color: '#8b949e', mb: 2 }}>
                      No records loaded yet
                    </Typography>
                    <Typography variant="body2" sx={{ color: '#8b949e' }}>
                      Click the button above to pull FSBO records
                    </Typography>
                  </Box>
                )}
              </>
            )}
          </Box>
        </Paper>
      </Grid>
    </Grid>
  );
};

export default TrialComponent;